package lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁  (自己的自旋锁实现)
 * @author jiangwz
 * @create 2019/9/14.
 */
public class SpinLockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock(){

        Thread thread = Thread.currentThread();
//        System.out.println(Thread.currentThread().getName());
        while (!atomicReference.compareAndSet(null, thread)){
            // 类似于Unsafe类的自旋一样
        }

    }

    public void unLock(){
        Thread thread = Thread.currentThread();
//        System.out.println(Thread.currentThread().getName());
        atomicReference.compareAndSet(thread, null);
    }



    public static void main(String[] args){

        SpinLockDemo lock = new SpinLockDemo();
        new Thread(() -> {
            lock.myLock();
            System.out.println(Thread.currentThread().getName()+"获取到锁");
            try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
            System.out.println(Thread.currentThread().getName()+"释放锁");
            lock.unLock();
        }, "aa").start();

        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        
        new Thread(() -> {
            lock.myLock();
            System.out.println(Thread.currentThread().getName()+"获取到锁");
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
            System.out.println(Thread.currentThread().getName()+"释放锁");
            lock.unLock();
        }, "bb").start();
    }

}
